<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:10px">
      <el-button
        type="primary"
        @click=" crrr()"
      >
        添加用户
      </el-button>
      <template>
        <el-table
          :data="rolesList"
          border
          style="width: 100%;margin-top:10px"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- 一级权限 -->
              <el-row
                :class="['bdbottom',li===0?'bdtop' :'']"
                v-for="(item1,li) in scope.row.children"
                :key="item1.id"
              >
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="removebyid(scope.row,item1.id)"
                  >
                    {{item1.authName}}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级 三级权限 -->
                <el-col :span="19">
                  <el-row
                    :class="[i2 ===0 ? '':'bdtop']"
                    v-for="(item2,i2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                        @close="removebyid(scope.row,item2.id)"
                      >
                        {{item2.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        type="info"
                        v-for="(item3,i3) in item2.children"
                        :key="item3.id"
                        closable
                        @close="removebyid(scope.row,item3.id)"
                      >
                        {{item3.authName}} </el-tag>
                    </el-col>
                  </el-row>
                </el-col>

              </el-row>
              <!-- <pre>{{scope.row}}</pre> -->
            </template>

          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column
            prop="roleName"
            label="角色名称"
          >
          </el-table-column>
          <el-table-column
            prop="roleDesc"
            label="角色描述"
          >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="charoles(scope.row),dialogVisible=true"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="deleteRoles(scope.row)"
              >删除</el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="fenpeiquanxian(scope.row)"
              >分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 添加角色 -->
    <el-card
      class="box-card"
      v-show="create"
    >
      <el-form
        :model="createRole"
        ref="createRole"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="角色名"
          prop="roleName"
        >
          <el-input v-model="createRole.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input v-model="createRole.roleDesc"></el-input>
        </el-form-item>
        <el-button
          type="primary"
          @click="submitForm('createRole')"
        >创建</el-button>
        <el-button @click="resetForm('createRole')">重置</el-button>
      </el-form>
    </el-card>
    <!-- 编辑角色 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="charoleList"
        label-width="80px"
      >
        <el-form-item
          label="角色名"
          prop="roleName"
        >
          <el-input v-model="charoleList.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input v-model="charoleList.roleDesc"></el-input>
        </el-form-item>

      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="xiugaiRole(),dialogVisible=false"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="feipei"
      width="50%"
    >
      <el-tree
        :data="rightList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkey"
        ref="treeRef"
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="feipei = false">取 消</el-button>
        <el-button
          type="primary"
          @click="allotRight(),feipei = false"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      dialogVisible: false,
      feipei: false,
      create: false,
      createRole: {
        roleName: "",
        roleDesc: "",
      },
      charoleList: {},
      rightList: [],
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
      },
      defaultProps: {
        label: "authName",
        children: "children",
      },
      defkey: [],
      roleId:'',
    };
  },
  created() {
    this.getrolesList();
  },
  methods: {
    //获取角色列表
    async getrolesList() {
      const res = await this.$http.get("roles");
      console.log(res);
      if (res.data.meta.status !== 200) return this.$message.error("获取失败");
      this.rolesList = res.data.data;
      console.log(this.rolesList);
    },
    //id查用户
    async charoles(roleInfo) {
      const res = await this.$http.get(`roles/${roleInfo.id}`);
      if (res.data.meta.status !== 200) return this.$message.error("获取失败");
      this.charoleList = res.data.data;
    },
    //修改角色
    async xiugaiRole() {
      const res = await this.$http.put("roles/" + this.charoleList.roleId, {
        roleName: this.charoleList.roleName,
        roleDesc: this.charoleList.roleDesc,
      });
      console.log(res);
      if (res.data.meta.status !== 200) return this.$message.error("修改失败");
      this.$message.success("更新成功");
      this.getrolesList();
    },
    //删除用户
    deleteRoles(roleInfo) {
      this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete(`roles/${roleInfo.id}`);
          console.log(res.data);
          this.getrolesList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //
    crrr() {
      this.create = !this.create;
    },
    //删除用户指定权限
    removebyid(role, rightId) {
      this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          console.log(res.data);
          role.children = res.data.data;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "删除未成功",
          });
        });
    },
    // 递归获取三级权限id
    getListKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
      this.getListKey(item, arr)
      )
    },

    //分配用户权限
    async fenpeiquanxian(role) {
      this.roleId=role.id
      const res = await this.$http.get("rights/tree");
      // console.log(res.data);
      this.rightList = res.data.data;
      this.defkey=[]
      this.getListKey(role,this.defkey)
      // console.log(this.defkey);
      this.feipei=true
      // console.log(this.rightList);
    },
    //更新用户权限
   async allotRight(){
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys);

      const idStr=keys.join(',')
    const res= await  this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
    if (res.data.meta.status !== 200) return this.$message.error("修改失败");
    this.$message.success('成功')
    this.getrolesList()
    },
    //创建用户
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post("roles", this.createRole);
          console.log(res.data);
          this.getrolesList();
          this.$message.success("创建成功");
          this.crrr();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.box-card {
  position: absolute;
  top: 200px;
  left: 450px;
}

.el-tag {
  margin: 8px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
